// src/controllers/backupController.js
const backupService = require('../services/backupService');
const fs = require('fs-extra');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { fileList } = require('../utils/fileUtils');

/**
 * 获取备份列表
 */
exports.getBackupList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, backupType = 'all', dataYear = '' } = req.query;
    

    console.log('dataYear: ',dataYear);
    // 计算分页参数
    const limit = parseInt(pageSize);
    const offset = (parseInt(page) - 1) * limit;
    
    // 处理backupType参数，如果为'all'则传null给服务层
    const type = backupType === 'all' ? null : backupType;
    
    // 调用服务层获取备份列表
    const result = await backupService.getBackupList(type, limit, offset, dataYear);
    
    if (result.success) {
      return res.json({
        code: 200,
        message: "获取备份列表成功",
        data: {
          total: result.total,
          list: result.data
        }
      });
    } else {
      return res.status(500).json({
        code: 500,
        message: "获取备份列表失败",
        error: result.error
      });
    }
  } catch (error) {
    console.error('获取备份列表出错:', error);
    return res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error: error.message
    });
  }
};

/**
 * 创建全量备份到自定义路径
 */
exports.createFullBackupToCustomPath = async (req, res) => {
  try {
    const { storagePath, password } = req.body;
    
    if (!storagePath) {
      return res.status(400).json({
        code: 400,
        message: "存储路径不能为空"
      });
    }
    
    // 确保目标目录存在
    fs.ensureDirSync(storagePath);
    console.log('storagePath: ',storagePath);
   

    // 调用备份服务执行全量备份
    const result = await backupService.fullBackup(password);
    
    if (result.success) {
      // 从默认备份位置复制到自定义路径
      const backupFileName = path.basename(result.path);
      const destPath = path.join(storagePath, backupFileName);
      
      // 复制文件
      await fs.copy(result.path, destPath);
      
      return res.json({
        code: 200,
        message: "全量备份创建成功",
        data: {
          filename: backupFileName,
          path: destPath,
          size: result.size,
          passwordHint: result.passwordHint
        }
      });
    } else {
      return res.status(500).json({
        code: 500,
        message: "全量备份创建失败",
        error: result.error
      });
    }
  } catch (error) {
    console.error('创建全量备份出错:', error);
    return res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error: error.message
    });
  }
};

/**
 * 创建增量备份到自定义路径
 */
exports.createIncrementalBackupToCustomPath = async (req, res) => {
  try {
    const { storagePath, password } = req.body;
    
    if (!storagePath) {
      return res.status(400).json({
        code: 400,
        message: "存储路径不能为空"
      });
    }
    
    // 确保目标目录存在
    fs.ensureDirSync(storagePath);
    
    // 调用备份服务执行增量备份
    const result = await backupService.incrementalBackup(password);
    
    if (result.success) {
      // 从默认备份位置复制到自定义路径
      const backupFileName = path.basename(result.path);
      const destPath = path.join(storagePath, backupFileName);
      
      // 复制文件
      await fs.copy(result.path, destPath);
      
      return res.json({
        code: 200,
        message: "增量备份创建成功",
        data: {
          filename: backupFileName,
          path: destPath,
          size: result.size,
          range: result.range,
          passwordHint: result.passwordHint
        }
      });
    } else {
      return res.status(500).json({
        code: 500,
        message: "增量备份创建失败",
        error: result.error
      });
    }
  } catch (error) {
    console.error('创建增量备份出错:', error);
    return res.status(500).json({
      code: 500,
      message: "服务器内部错误",
      error: error.message
    });
  }
};

/**
 * 从上传的文件还原备份
 * @param {Object} req Express请求对象
 * @param {Object} res Express响应对象
 */
exports.restoreBackupFromUpload = async (req, res) => {
  try {
    console.log('接收到备份还原请求');
    
    // 验证是否有文件上传
    if (!req.files || !req.files.backup) {
      return res.status(400).json({
        code: 400,
        message: '未找到上传的备份文件',
        data: null
      });
    }
    
    const backupFile = req.files.backup;
    const password = req.body.password;

    if (backupFile.data.length === 0 && backupFile.tempFilePath) {
      backupFile.data = fs.readFileSync(backupFile.tempFilePath);
    }

    
    const options = {
      conflictStrategy: req.body.strategy || 'replace',
      backupBeforeRestore: req.body.backupBeforeRestore !== false,
      ignoreErrors: req.body.ignoreErrors === true
    };
    
    console.log('备份还原参数:', {
      fileName: backupFile.name,
      fileSize: backupFile.size,
      mimeType: backupFile.mimetype,
      hasPassword: !!password,
      options
    });
    
 
    const result = await backupService.restoreBackup(
      {
        originalname: backupFile.name,
        mimetype: backupFile.mimetype,
        data: backupFile.data,
        size: backupFile.size
      },
      password,
      options
    );
    
    console.log('备份还原服务调用完成, 结果:', result.success ? '成功' : '失败');
    
    if (!result.success) {
      return res.status(400).json({
        code: 400,
        message: result.error,
        data: result.details || null
      });
    }
    
    return res.json({
      code: 200,
      message: result.message,
      data: {
        restoredFiles: result.restoredFiles,
        totalFiles: result.totalFiles,
        strategy: result.strategy,
        errors: result.errors
      }
    });
    
  } catch (error) {
    console.error('备份还原失败:', error);
    return res.status(500).json({
      code: 500,
      message: `备份还原失败: ${error.message}`,
      data: null
    });
  }
};


// 根据备份ID还原备份
exports.restoreBackupById = async (req, res) => {
  try {
    const { backupId } = req.query;
 

    const result = await backupService.restoreBackup(backupId);

    return res.json(result);
  } catch (error) {
    console.error('备份还原失败:', error);
    return res.status(500).json({ 
      code: 500,
      message: `备份还原失败: ${error.message}`,
      data: null
    });
  }
};


/**
 * 获取文件夹列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getFileList = async (req, res) => {
  try {
    const dirPath = req.query.path || '';
    const result = await fileList(dirPath);
    return res.json(result);
  } catch (error) {
    console.error('获取文件列表出错:', error);
    return res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
}




